"""
CSPBuilder stats functions

Copyright (c) 2008 Rune M. Friborg, runef@diku.dk.
See LICENSE.txt for licensing details (GPLv2).
"""

import time

COUNTS = {}
PROFILING = {}
profiling_next_order = 1
ORDER = {}

def addTo(id, count):
    if (not COUNTS.has_key(id)):
        COUNTS[id] = count
    else:
        COUNTS[id] = COUNTS[id] + count


def profileStart(id):
    t = int(time.time() * 1000000)
    PROFILING[id] = t


def profileEnd(id):
    global profiling_next_order
    t = int(time.time() * 1000000)
    setOrder(id, profiling_next_order)
    profiling_next_order += 1
    PROFILING[id] = t - PROFILING[id]


def setOrder(id, order = 1):
    if ORDER.has_key(order):
        ORDER[order].append(id)
    else:
        ORDER[order] = [id]

def getFormattedCounts():
    s = 40*'-' + '\n'
    for id_l in ORDER:
        for id in ORDER[id_l]:
            if id in COUNTS.keys():
                s += id + ": " + str(COUNTS[id]) + '\n'
    s += 40*'-'
    return s

def getFormattedProfiling():

    s = 40*'-' + '\n'
    for id_l in ORDER:
        for id in ORDER[id_l]:
            if id in PROFILING.keys():
                time_str = str(PROFILING[id])
                s += id + ": " + time_str[:-3] + "." + time_str[-3:] + 'ms\n'
    s += 40*'-'
    return s






